/**************************************************************************
*   Copyright (C) 2009 Chernov Dmitry                                     *
*   diman4ik.chernov@gmail.com                                            *
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*                                                                         *
*   This program is distributed in the hope that it will be useful,       *
*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
*   GNU General Public License for more details.                          *
*                                                                         *
*   You should have received a copy of the GNU General Public License     *
*   along with this program; if not, write to the                         *
*   Free Software Foundation, Inc.,                                       *
*   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
***************************************************************************/

#include "korners_window.h"
#include "korners_widget.h"
#include "korners_render.h"
#include "korners_scene.h"
#include "build/korners.h"

#include "korners_netgame_dialog.h"
#include "korners_netgame_dialog_ip.h"
#include "korners_netgame_settings.h"

#include <KStatusBar>
#include <KLocale>
#include <KAction>
#include <KActionCollection>
#include <KStandardAction>
#include <KStandardGameAction>
#include <KGameThemeSelector>
#include <KIcon>
#include <KScoreDialog>
#include <KConfigDialog>
#include <KToggleAction>
#include <KMessageBox>


KornersMainWindow::KornersMainWindow()
{
    m_widget = new KornersWidget( this );
    setCentralWidget( m_widget );

    connect( m_widget->scene(), SIGNAL( gameOver(QTime) ), SLOT( gameOver(QTime) ) );
    connect( m_widget->scene(), SIGNAL( started() ), SLOT( gameStarted() ) );
    connect( m_widget->scene(), SIGNAL( newStatus1(QString) ), SLOT( showStatus1(QString) ) );
    connect( m_widget->scene(), SIGNAL( newStatus2(QString) ), SLOT( showStatus2(QString) ) );
    statusBar()->insertItem( i18n(" "), 0 );
    statusBar()->insertItem( i18n(" "), 1 );

    statusBar()->setSizeGripEnabled(true);
    setupActions();
    //Prefs::setOnTime(false);
}

void KornersMainWindow::setupActions()
{
    // Game 
    KAction* dualAction = new KAction(this);
    dualAction->setText( i18n("Local multiplayer") );
    actionCollection()->addAction( "dual", dualAction );
    connect( dualAction, SIGNAL( triggered(bool) ), SLOT( localMultiplayerGame() ) );

    KAction* connectAction = new KAction(this);
    connectAction->setText( i18n("Connect to LAN game") );
    actionCollection()->addAction( "connect", connectAction );
    connect( connectAction, SIGNAL( triggered(bool) ), SLOT( connectToNetworkGame() ) );

    KAction* createAction = new KAction(this);
    createAction->setText( i18n("Create  LAN game") );
    actionCollection()->addAction( "create", createAction );
    connect( createAction, SIGNAL( triggered(bool) ), SLOT( createNetworkGame() ) );

    KStandardGameAction::gameNew( this, SLOT( startGame() ), actionCollection() );
    KStandardGameAction::highscores( this, SLOT( viewHighScore() ), actionCollection() );
    KStandardGameAction::quit( this, SLOT( close() ), actionCollection() );

    // Preferences
    KToggleAction* onTime = actionCollection()->add<KToggleAction>("on_time");
    onTime->setText( i18n( "Time game" ) );
    connect( onTime, SIGNAL( triggered(bool) ), SLOT( onTimeToggled(bool) ) );

    KStandardAction::preferences( this, SLOT( configureSettings() ), actionCollection() );
    setupGUI();
}

void KornersMainWindow::gameOver( QTime time )
{
    // Results are ranged by time
    if( Prefs::onTime() )
    {
        if( !( ( time.hour() == 0 ) && ( time.minute() == 0 ) && ( time.second() == 0 ) ) )
        {
            // If you played about 10 hours score would be close to 0 :)
            int score = 36000 - ( time.hour()*3600 + time.minute()*60 + time.second() )%36000;

            KScoreDialog::FieldInfo scoreInfo;
            scoreInfo[KScoreDialog::Score].setNum(score);
            scoreInfo[KScoreDialog::Time] = time.toString();

            KScoreDialog d( KScoreDialog::Name | KScoreDialog::Time, this );
            //d.setConfigGroup( i18n("Highscore") );
            d.addScore( scoreInfo, KScoreDialog::AskName );
            d.exec();
        }
    }
    actionCollection()->action("on_time")->setEnabled(true);    
}

void KornersMainWindow::gameStarted()
{
    actionCollection()->action("on_time")->setEnabled(false);
}

void KornersMainWindow::viewHighScore()
{
    KScoreDialog d( KScoreDialog::Name | KScoreDialog::Time, this );
    //d.setConfigGroup( i18n("Highscore") );
    d.exec();
}

void KornersMainWindow::startGame()
{
    setWindowTitle("Korners Game");
    clearStatus();
    actionCollection()->action("on_time")->setEnabled(true);
    m_widget->scene()->startNewLocalGame(false);
}

void KornersMainWindow::localMultiplayerGame()
{
    setWindowTitle("Korners Game");
    clearStatus();
    m_widget->scene()->startNewLocalGame(true);
}

void KornersMainWindow::configureSettings()
{
    if ( KConfigDialog::showDialog( "settings" ) )
        return;

    KConfigDialog *dialog = new KConfigDialog( this, "settings", Prefs::self() );
    dialog->addPage( new KGameThemeSelector( dialog, Prefs::self(), 
                                             KGameThemeSelector::NewStuffDisableDownload  ), 
                                             i18n( "Theme" ), "games-config-theme" );
    dialog->addPage( new KornersNetgameSettings( dialog, Prefs::self() ), i18n("Network"), "neat" );
    connect( dialog, SIGNAL( settingsChanged(const QString&) ), this, SLOT( loadSettings() ) );

    dialog->setHelp( QString(),"korners" );
    dialog->show();
}

void KornersMainWindow::loadSettings()
{
    if ( !KornersRender::self()->loadTheme( Prefs::theme() ) )
    {
        KMessageBox::error( this,  
                            i18n( "Failed to load \"%1\" theme. Please check your installation.",
                            Prefs::theme() ) );
        return;
    }
    QRectF r = m_widget->scene()->sceneRect();
    m_widget->scene()->invalidate( r, QGraphicsScene::BackgroundLayer ); // redraw background
    m_widget->scene()->resizeScene( (int)r.width(), (int)r.height() );   // redraw scene
}

void KornersMainWindow::onTimeToggled( bool onTime )
{
    Prefs::setOnTime(onTime);
    m_widget->scene()->toggleOnTime( onTime );
}

void KornersMainWindow::connectToNetworkGame()
{
    setWindowTitle("Korners : client");
    clearStatus();

    KornersNetgameDialogIp* dialog = new KornersNetgameDialogIp(this);
    connect( dialog, SIGNAL( userName( QString, QString ) ), SLOT( playerNameIp( QString, QString ) ) );
    dialog->exec();
}

void KornersMainWindow::playerNameIp( QString name, QString ip )
{
    int port = Prefs::network().toInt();
    m_widget->scene()->startNetworkGameClient( name, port, ip );
}

void KornersMainWindow::playerName( QString name )
{
    int port = Prefs::network().toInt();
    m_widget->scene()->startNetworkGameServer( name, port ); 
}

void KornersMainWindow::createNetworkGame()
{
    setWindowTitle("Korners : server");
    clearStatus();

    KornersNetgameDialog* dialog = new KornersNetgameDialog(this);
    connect( dialog, SIGNAL( userName( QString ) ), SLOT( playerName( QString ) ) );
    dialog->exec();
}

void KornersMainWindow::showStatus1( QString text )
{
    statusBar()->changeItem( text, 0);
}

void KornersMainWindow::showStatus2( QString text )
{
    statusBar()->changeItem( text, 1);
}

void KornersMainWindow::clearStatus()
{
    statusBar()->changeItem( " ", 0);
    statusBar()->changeItem( " ", 1);
}
